import axios from 'axios';
import router from '../router';
import Vue from "vue";
axios.defaults.timeout = 30000;
axios.defaults.baseURL = '';
Vue.prototype.$http = axios; // 并发请求
//http request 拦截器
axios.interceptors.request.use((config) => {
	// if (localStorage.token) {
	// 	const token = localStorage.token;
		// if (config.url.indexOf('spider.extfans.com') < 0) {
	//添加权限token
	if(sessionStorage.token){
		store.state.authToken = sessionStorage.token
	}
	config.headers = {
		'Content-Type': 'application/json;charset=UTF-8'
	}
	//添加权限token
    if (sessionStorage.token) {
		config.headers["token"] = store.state.authToken;
	}
	return config;
}, (error) => {
	return Promise.reject(error);
});
// 
// http response 拦截器
axios.interceptors.response.use(
	response => {
		// if (response.data.authenticate) {
		// 	localStorage.token = response.data.authenticate.access_token
		// }
		// if (response.data.code == 400) {
		// 	localStorage.adminName = ''
		// 	localStorage.token = ''
		// 	localStorage.type = ''
		// 	router.push({
		// 		path: '/'
		// 	})
		// }
		return response;
	},
	error => {
		return Promise.reject(error)
	}
)
if (process.env.NODE_ENV === 'production') {
	// axios.defaults.baseURL = '';
} else {
	axios.defaults.baseURL = '/entrance';
}
// get，post请求方法
export default {
	/**
	 * 封装post请求
	 * @param url
	 * @param data
	 * @returns {Promise}
	 */
	post(url, data = {}) {
		return new Promise((resolve, reject) => {
			axios.post(url, data)
				.then(response => {
					if(response.data.code == 400){
						router.push({
							path: '/'
						})
					}
					resolve(response.data);
				}, err => {
					console.log(err)
					// Message.error(err);
					reject(err)
				})
		})
	},
	/**
 * 封装get方法
 * @param url
 * @param data
 * @returns {Promise}
 */
	get(url, params = {}) {
		return new Promise((resolve, reject) => {
			axios.get(url, {
				params: params
			})
				.then(response => {
					resolve(response);
				})
				.catch(err => {
					// Message.error(err);
					reject(err)
				})
		})
	}
};
